package middleware

import (
	"bytes"
	"io/ioutil"
	"net/http"
	"xwWechatPublic/utils/logging"
)

//get请求
func HttpRequest(url string) (body []byte, err error) {
	logging.Debug("HttpRequest ...")
	logging.Info("Get URL[%v]", url)
	resp, err := http.Get(url)
	if err != nil {
		defer resp.Body.Close()
		logging.Info("Get URL Error [%v]", err.Error())
		return body, err
	}
	defer resp.Body.Close()

	body, err = ioutil.ReadAll(resp.Body)
	logging.Info("body[%v]", string(body))
	return body, err
}

//POST发送json报文
func HttpPostJsonRequest(url string, jsonStr []byte) (body []byte, err error) {
	logging.Info("POST:", url)

	//var jsonStr = []byte(params)
	logging.Info("jsonStr", string(jsonStr))
	logging.Debug("new_str", bytes.NewBuffer(jsonStr))

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
	// req.Header.Set("X-Custom-Header", "myvalue")
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	logging.Info("response Status:", resp.Status)
	logging.Info("response Headers:", resp.Header)
	body, err = ioutil.ReadAll(resp.Body)
	logging.Info("response Body:", string(body))
	return body, err
}
